/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mballs;

import java.awt.*;

/**
 *
 * @author menderleit
 */
public class DoubleBuffer extends Canvas {
    public DoubleBuffer() {
        super();
    }
    
    @Override
    public void update(Graphics g) {
        paint(g);
    }
    
    private int bufferWidth;
    private int bufferHeight;
    private Image bufferImage;
    private Graphics bufferGraphics;
    
    @Override
    public void paint(Graphics g) {
        // Make sure we have a valid backbuffer.
        if(bufferWidth != getSize().width || bufferHeight != getSize().height || bufferImage == null || bufferGraphics == null) {
            resetBuffer();
        }

        if(bufferGraphics != null) {
            // Clear the backbuffer.
            bufferGraphics.clearRect(0, 0, bufferWidth, bufferHeight);

            // Call paintBuffer to actually draw to the backbuffer.
            paintBuffer(bufferGraphics);

            // Copy the backbuffer to the frontbuffer.
            g.drawImage(bufferImage, 0, 0, this);
        }
    }
    
    private void resetBuffer(){
        // always keep track of the image size
        bufferWidth = getSize().width;
        bufferHeight = getSize().height;

        //    clean up the previous image
        if(bufferGraphics != null){
            bufferGraphics.dispose();
            bufferGraphics = null;
        }
        if(bufferImage != null){
            bufferImage.flush();
            bufferImage = null;
        }
        //System.gc();

        //    create the new image with the size of the panel
        bufferImage = createImage(bufferWidth,bufferHeight);
        bufferGraphics = bufferImage.getGraphics();
    }
    
    public void paintBuffer(Graphics g){
        //in classes extended from this one, add something to paint here!
        //always remember, g is the offscreen graphics
    }
}
